<template>
  <div class="trafficMasterMgt">
    <div class="content-table">
      <div class="form-content flexrowbetween">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <el-form-item label="用户名" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="会员ID" prop="id">
            <el-input
              v-model="queryParams.id"
              placeholder="请输入会员ID"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="信息审核状态" prop="check_status">
            <el-select
              v-model="queryParams.check_status"
              placeholder="请选择信息审核状态"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dict in statusList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结单审核状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择资结单核状态"
              clearable
              @change="handleQuery"
              style="width: 200px"
            >
              <el-option
                v-for="dict in checkStatusList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="结算时间" prop="timeRange">
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索
            </el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="table-content">
        <div class="table-group">
          <div class="group-right">
            <el-button size="mini" type="primary" @click="handleExport()" v-hasPermi="['trafficMgt:export']">导出</el-button>
          </div>
        </div>
        <div class="table-big">
          <el-table
            :data="tableDataList"
            ref="advergroupTable"
            :max-height="tableHeight"
            class="tableHightClass"
          >
            <el-table-column
              :label="item.label"
              align="center"
              v-for="(item, index) in tableColumns"
              :key="index"
              :prop="item.key"
              :min-width="item.minWidth ? item.minWidth : ``"
              :fixed="item.fixed ? item.fixed : false"
              :show-overflow-tooltip="true"
            >
              <!--用于表格自定义-->
              <template slot-scope="scope">
                <!--状态-->
                <div v-if="item.key == 'status'">
                  <el-switch
                    v-model="scope.row[item.key]"
                    @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </div>
                <div v-else-if="item.key == 'status_name'" class="status">
                  <span
                    :class="scope.row.status == 1 ? `color-green` : `color-red`"
                  >{{ scope.row[item.key] }}</span
                  >
                </div>
                <div v-else>{{ scope.row[item.key] }}</div>
              </template>
            </el-table-column>

            <el-table-column
              prop="created_at"
              label="操作"
              width="420"
              fixed="right"
              align="center"
            >
              <template slot-scope="scope">
                <div class="flexcenter btnflex">
                  <div class="commhover mr_10 c_primary" @click="handleGround(scope.row)"  v-hasPermi="['trafficMgt:goto']">前台</div>
                  <div class="commhover mr_10 c_primary" @click="handleUpdate(scope.row)" v-hasPermi="['trafficMgt:edit']">编辑</div>
                  <div class="commhover mr_10 c_primary"  v-hasPermi="['trafficMgt:account']" v-if="scope.row.check_status && scope.row.check_status !=0 && scope.row.check_status !=8">
                    <span v-if="scope.row.check_status==5" @click=" handleView(scope.row)">结单</span>
                    <span v-else @click="handleFinsh(scope.row)">结单</span>
                  </div>
                  <div class="commhover mr_10 c_primary" @click="handleInfo(scope.row)" v-hasPermi="['trafficMgt:infoExamine']"  v-if="scope.row.status==0">信息审核</div>
                  <div class="commhover mr_10 c_primary" @click="handleOrder(scope.row)" v-hasPermi="['trafficMgt:accountExamine']"  v-if="scope.row.check_status==0 && scope.row.check_pay">结算单审核</div>
                  <div class="commhover mr_10 c_primary" @click="handledownSettle(scope.row)" v-hasPermi="['trafficMgt:downAccount']" v-if="scope.row.check_status>0 && scope.row.check_status<8">下载结算单</div>
                    <div class="commhover mr_10 c_primary" @click="handleView(scope.row)" v-hasPermi="['trafficMgt:view']" v-if="scope.row.check_status && scope.row.check_status !=0 && scope.row.check_status !=8">查看结单</div>
                  <div class="commhover mr_10 c_primary" v-hasPermi="['trafficMgt:history']" @click="handleHistoryData(scope.row)"  v-if="scope.row.check_pay">历史数据</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.num"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
    <!--    编辑-->
    <edit-master v-if="openEdit" :visableIf.sync="openEdit" :rowitem='rowitem' @getList="getList"/>
    <!--    结算单审核-->
    <check-order v-if="openorder" :visableIf.sync="openorder" :rowitem='rowitem' :jd_id="jd_id" @getList="getList"/>
    <!--    结单-->
    <finish-master v-if="openFinish" :visableIf.sync="openFinish" :rowitem='rowitem' @getList="getList"/>

    <viewFinishMaster v-if="openView" :visableIf.sync="openView" :rowitem='rowitem' @getList="getList"></viewFinishMaster>
    <!--    信息审核-->
    <check-info v-if="openInfo" :visableIf.sync="openInfo" :rowitem='rowitem' @getList="getList"/>
    <historyData v-if="showHistory" :visableIf.sync="showHistory" :id='id' :queryParams="queryParams"></historyData>
  </div>
</template>
<script>
import { reqTrafficList, reqTrafficPayStatus, reqTrafficInfoStatus, reqIndexExport, reqTrafficPosition,reqPayDataInfoExport } from '@/api/trafficMasterMgt/index'
import EditMaster from './EditMaster.vue'
import CheckOrder from './CheckOrder.vue'
import FinishMaster from './FinishMaster.vue'
import viewFinishMaster from './viewFinishMaster.vue'
import CheckInfo from './CheckInfo.vue'
import historyData from './historyData.vue'
import { getCustomToken } from '@/api/advmaster'
import { getToken } from '@/utils/auth'

export default {
  name: 'coordinateList',
  data() {
    return {
      // 查询参数
      total: 8, // 表格的总条数
      openorder: false, //结算单审核
      tableHeight: null,
      id: null, //id
      jd_id: null,//
      queryParams: {
        page: 1,
        num: 10,
        name: '', //名字
        id: null,
        status: null, //结单状态
        check_status: null,
        start: null, //开始时间
        end: null //结束时间
      },
      timeRange: [],
      statusList: [], //状态集合
      tableDataList: [], //表格数据
      checkStatusList: [], //
      tableColumns: [
        { key: 'id', label: `ID`, visible: true, fixed: false },
        { key: 'name', label: `用户名`, visible: true, minWidth: 150, fixed: false },
        { key: 'mobile', label: `手机号`, visible: true, minWidth: 150, fixed: false },
        { key: 'email', label: `邮箱`, visible: true, minWidth: 200 },
        { key: 'last_login_time', label: `登录时间`, visible: true, minWidth: 200 },
        { key: 'create_time', label: `注册时间`, visible: true, minWidth: 200 },
        { key: 'check_payCreate_time', label: `结算时间`, visible: true, minWidth: 200 },
        { key: 'check_payStatus_name', label: `结单审核状态`, visible: true, minWidth: 150 },
        { key: 'account_infoStatus_name', label: `信息审核状态`, visible: true, minWidth: 150 },
        { key: 'all_num', label: `广告位总数量`, visible: true, minWidth: 150 },
        { key: 'open_num', label: `已开启广告位总数量`, visible: true, minWidth: 150 },
        { key: 'check_num', label: `本月结算次数`, visible: true, minWidth: 150 },
        { key: 'waiting_coin', label: `未结算金额`, visible: true, minWidth: 150 },
        { key: 'month_coin', label: `本月结算金额`, visible: true, minWidth: 150 },
        { key: 'settled_amount', label: `累计结算金额`, visible: true, minWidth: 150 }
      ],
      exportColumns: [
        { key: 'custom.id', label: `ID`, visible: true, fixed: false },
        { key: 'custom.user_login', label: `用户名`, visible: true, minWidth: 150, fixed: false },
        { key: 'custom.mobile', label: `手机号`, visible: true, minWidth: 150, fixed: false },
        { key: 'custom.email', label: `邮箱`, visible: true, minWidth: 150 },
        { key: 'custom.last_login_time', label: `登录时间`, visible: true, minWidth: 150 },
        { key: 'custom.create_time', label: `注册时间`, visible: true, minWidth: 150 },
        { key: 'check_pay.create_time', label: `结算时间`, visible: true, minWidth: 150 },
        { key: 'check_pay.status_name', label: `结单审核状态`, visible: true, minWidth: 150 },
        { key: 'account_info.status_name', label: `信息审核状态`, visible: true, minWidth: 150 },
        { key: 'position_data.all_num', label: `广告位总数量`, visible: true, minWidth: 150 },
        { key: 'position_data.open_num', label: `已开启广告位总数量`, visible: true, minWidth: 150 },
        { key: 'check_data.check_num', label: `本月结算次数`, visible: true, minWidth: 150 },
        { key: 'check_data.waiting_coin', label: `未结算金额`, visible: true, minWidth: 150 },
        { key: 'check_data.month_coin', label: `本月结算金额`, visible: true, minWidth: 150 },
        { key: 'settled_amount', label: `累计结算金额`, visible: true, minWidth: 150 }
      ],
      exportMentColumns: [],
      columnsFields: [], //自定义列表的字段集合
      openEdit: false,
      rowitem: null,
      openFinish: false,//结单
      openInfo: false,//信息审核
      showHistory: false,//查看历史记录
      openView:false,
      positionList:[],
    }
  },
  components: {
    EditMaster,
    CheckOrder,
    FinishMaster,
    CheckInfo,
    historyData,
    viewFinishMaster,
  },
  created() {
    this.getList()
    this.tableColumns.forEach((item) => {
      this.columnsFields.push(item.label)
    })
    this.getCustomCheckStatus() //结单审核
    this.getTrafficInfoStatus()//信息审核
  },
  watch: {
    tableDataList: {
      handler(val) {
        if (val.length > 0) {
          this.getTabelHeight() //获取表格的最大高度
          this.getTableContentHeight() //获取整体的高度
          this.$refs.advergroupTable.doLayout()
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getTabelHeight() //获取表格的最大高度
    this.getTableContentHeight() //获取整体的高度
    window.onresize = () => {
      return (() => {
        this.getTabelHeight() //获取表格的最大高度
        this.getTableContentHeight() //获取整体的高度
        this.$refs.advergroupTable.doLayout()
      })()
    }
  },

  methods: {
    handleGround(row){
      getCustomToken({id:row.custom_id}).then(res=>{
        let token = res.data;
        //  + "&activeId=" + row.id
        console.log('getToken----',getToken());
        window.open(
          this.userdomain + 'login?token=' + token + '&adminToken=' + getToken() +'&custom=1',
        );
      })
    },
    getExportMentColumns(row){
      let form = {};
      let head = [];
      let keys = [];
      for (let key in form) {
        if (!form[key]) {
          delete form[key]
        }
      }
      this.exportMentColumns.forEach(item => {
        head.push(item.label)
        keys.push(item.key)
      })
      form.id=row.custom_id;
      form.head = head
      form.keys = keys
      delete form.page
      delete form.num
      reqPayDataInfoExport(form).then((res) => {
        if (res.code == 1) {
          const a = document.createElement('a')
          document.body.appendChild(a)
          a.download = '结算单.xls'
          a.href = res.data
          a.click()
          document.body.removeChild(a)
        }

      })
    },
    handledownSettle(row){
      //下载结算单
     this.getTrafficPosition(row); //获取广告位

    },
    getTrafficPosition(row) {
      //获流量的广告位
      this.positionList=[];
      this.exportMentColumns=[
        { key: 'create_time', label: `日期`, },
        { key: 'all_coin', label: `总收入` },
      ]
      reqTrafficPosition({ id: row.custom_id }).then(res => {
        this.positionList = res.data;
        this.positionList.forEach(item => {
                let obj= {
                  key: 'list_data.'+item.id,
                  label:item.name,
                }
                this.exportMentColumns.push(obj);
        });
         this.getExportMentColumns(row);//下载结算单


      })
    },
    /** 导出按钮操作 */
    handleExport() {
      let form = JSON.parse(JSON.stringify(this.queryParams))
      let head = []
      let keys = []
      for (let key in form) {
        if (!form[key]) {
          delete form[key]
        }
      }
      this.exportColumns.forEach(item => {
        head.push(item.label)
        keys.push(item.key)
      })
      form.head = head
      form.keys = keys
      delete form.page
      delete form.num
      reqIndexExport(form).then((res) => {
        if (res.code == 1) {
          const a = document.createElement('a')
          document.body.appendChild(a)
          a.download = '流量主管理导出表.xls'
          a.href = res.data
          a.click()
          document.body.removeChild(a)
        }

      })

    },
    getCustomCheckStatus() {
      this.checkStatusList = []
      reqTrafficPayStatus().then((res) => {
        for (let key in res.data) {
          let obj = {
            value: key,
            label: res.data[key]
          }
          this.checkStatusList.push(obj)
        }
      })
    },
    getTrafficInfoStatus() {
      this.statusList = []
      reqTrafficInfoStatus().then((res) => {
        for (let key in res.data) {
          let obj = {
            value: key,
            label: res.data[key]
          }
          this.statusList.push(obj)
        }
      })
    },
    getTableContentHeight() {
      let topHeight = document.querySelector('.table-content').offsetTop
      let windowsHeight = document.body.clientHeight
      document.querySelector('.table-content').style.height =
        windowsHeight - topHeight - 80 + 'px'
    },
    getTabelHeight() {
      //获取表格的高度
      let topHeight = document.querySelector('.tableHightClass').offsetTop
      let windowsHeight = document.body.clientHeight
      if (this.total > 10) {
        let paginationContainerHeight = document.querySelector(
          '.pagination-container'
        ).clientHeight
        this.tableHeight =
          windowsHeight - topHeight - 20 - paginationContainerHeight - 80
      } else {
        this.tableHeight = windowsHeight - topHeight - 20
      }
    },
    handleStatusChange(row) {
      console.log('状态', row.status)
      let text = row.status == false ? '暂停' : '启用'
      this.$modal
        .confirm(`确认要${text}此账号（${row.user_login}）吗？`)
        .then(function() {
          if (row.status == false) {
            return reqCoordinateClose(row.id)
          } else {
            return reqCoordinateOpen(row.id)
          }
        })
        .then(() => {
          this.$modal.msgSuccess(text + '成功')
          this.getList()
        })
        .catch(function() {
          row.status = row.status == 1 ? false : true
        })
    },
    getList() {
      this.tableDataList = []
      this.loading = true
      if (this.timeRange && this.timeRange.length > 0) {
        this.queryParams.start = this.timeRange[0]
        this.queryParams.end = this.timeRange[1]
      } else {
        this.queryParams.start = null
        this.queryParams.end = null
      }
      let form = JSON.parse(JSON.stringify(this.queryParams))
      for (let key in form) {
        if (!form[key]) {
          delete form[key]
        }
      }
      reqTrafficList(form).then((res) => {
        this.tableDataList = res.data.list
        this.tableDataList.forEach((item) => {
          item.id = item.custom.id
          item.name = item.custom.user_login
          item.mobile = item.custom.mobile
          item.email = item.custom.email
          item.last_login_time = item.custom.last_login_time
          item.create_time = item.custom.create_time
          item.check_payCreate_time = item.check_pay && item.check_pay.create_time ? item.check_pay.create_time : `-`;
          item.check_payStatus_name = item.check_pay && item.check_pay.status_name ? item.check_pay.status_name : `-`;
          item.account_infoStatus_name =item.account_info &&item.account_info.status_name?item.account_info.status_name :'-';
          item.all_num = item.position_data.all_num
          item.open_num = item.position_data.open_num
          item.check_num = item.check_data.check_num
          item.waiting_coin = item.check_data.waiting_coin
          item.month_coin = item.check_data.month_coin
          item.status = item.account_info ? item.account_info.status : null
          item.check_status = item.check_pay ? item.check_pay.status : null
        })
        console.log('流量主信息', this.tableDataList)
        this.total = res.data.count
        this.loading = false
      })
    },
    //搜索
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    //重置表单
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleUpdate(row) {
      console.log('row', row)
      this.rowitem = row
      this.openEdit = true
    },

    // 结算单审核
    handleOrder(row) {
      this.jd_id = row.jd_id
      this.rowitem = row
      this.openorder = true
    },

    // 结单
    handleFinsh(row) {
      this.rowitem = row;
      this.openFinish = true
    },
    handleView(row){
      //查看结单
      this.rowitem = row;
      this.openView = true
    },
    handleInfo(row) {
      this.rowitem = row
      this.openInfo = true
    },
    //历史数据
    handleHistoryData(row) {
      this.id = row.id;
      this.queryParams.id=row.custom_id;
      this.showHistory = true;
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  .big-title {
    height: 40px;
    border-bottom: 1px solid #d5d5d5;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0px 24px;
  }

  .form-content {
    padding: 12px;
    background: #fff;
    margin-bottom: 10px;
  }

  /*表格通用代码编写，可用于全局*/
  .table-content {
    background: #fff;
    padding: 0px 15px;

    .table-group {
      display: flex;
      padding: 12px 0px;
      flex-wrap: wrap;

      .group-left {
        width: 200px;
        display: flex;
        flex-wrap: wrap;

        ::v-deep.el-button--primary {
          border: 1px solid #1670f1;
          background: none !important;
          color: #1670f1;
        }
      }

      .group-right {
        flex: 1;
        align-items: center;
        justify-content: flex-end;
        display: flex;

        .suspendBtn {
          background: #fb311e !important;
          border-color: #fb311e;
        }

        .exportBtn,
        .customStyle {
          border: 1px solid #1670f1;
          background: none !important;
          color: #1670f1;
        }
      }
    }

    /*表格样式*/
    .table-big {
      ::v-deep .el-table {
        .links {
          color: #1670f1;
          text-decoration: underline;
          cursor: pointer;
        }
      }
    }
  }
}

.tableList {
  display: flex;
  border-bottom: 1px solid #eee;
  background: #fff;
  padding: 0px 20px;
  margin: 0;
  height: 54px;
  border-bottom: 10px solid #f8f9fd;
  margin: 16px 0px 0 0px;

  li {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    padding: 0px 10px;
    position: relative;
    cursor: pointer;
    height: 44px;
    color: #8e8e8e;
    margin-right: 30px;

    &.active {
      font-weight: bold;
      color: #000;

      &:after {
        height: 2px;
        background: #1670f1;
        content: "";
        position: absolute;
        left: 10px;
        right: 10px;
        bottom: 0;
      }
    }
  }
}

.status {
  span {
    position: relative;
    padding-left: 15px;

    &:after {
      position: absolute;
      left: 0px;
      width: 9px;
      height: 9px;
      border-radius: 50%;
      content: "";
      top: 50%;
      margin-top: -4.5px;
    }

    &.color-green:after {
      background: #00dd33;
    }

    &.color-red:after {
      background: #d10807;
    }
  }
}

.columnsFields {
  overflow-y: auto;
  padding: 10px 10px;

  .el-checkbox-group {
    display: flex;
    flex-direction: column;

    .el-checkbox {
      width: 200px;
      margin-bottom: 5px;
    }
  }
}

.el-dropdown {
  margin-left: 10px;
}

.el-form-item {
  margin-bottom: 10px;
}
</style>
